#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 设置窗口为始终置顶
void set_always_on_top(Display *display, Window window) {
    Atom net_wm_state = XInternAtom(display, "_NET_WM_STATE", False);
    Atom net_wm_state_above = XInternAtom(display, "_NET_WM_STATE_ABOVE", False);
#if 0
    XEvent event;
    memset(&event, 0, sizeof(event));
    event.type = ClientMessage;
    event.xclient.window = window;
    event.xclient.message_type = net_wm_state;
    event.xclient.format = 32;
    event.xclient.data.l[0] = 1;  // _NET_WM_STATE_ADD
    event.xclient.data.l[1] = net_wm_state_above;
    event.xclient.data.l[2] = 0;

    XSendEvent(display, DefaultRootWindow(display), False,
               SubstructureRedirectMask | SubstructureNotifyMask, &event);
#else
    XChangeProperty(display, window, net_wm_state, XA_ATOM, 32, PropModeReplace,
                    (unsigned char *)&net_wm_state_above, 1);
#endif
    XSync(display, false);
}

// 设置窗口不获取焦点
void set_no_focus(Display *display, Window window) {
#if 0
    XWMHints *hints = XAllocWMHints();
    hints->flags = StateHint | InputHint;
    hints->input = False;  // 不接受输入
    hints->initial_state = NormalState;
    XSetWMHints(display, window, hints);
    XFree(hints);
    XSync(display, false);
#else
    XSetWindowAttributes attrs;
    //memset(&attrs, 0, sizeof(attrs));
    attrs.do_not_propagate_mask = /*ButtonPressMask | ButtonReleaseMask | */ FocusChangeMask;
    attrs.override_redirect = True;
    XChangeWindowAttributes(display, window, /* CWDontPropagate | */ CWOverrideRedirect, &attrs);
    XSync(display, false);
#endif
}

// 设置窗口为无边框（可选）
void set_decorations(Display *display, Window window) {
    Atom net_wm_window_type = XInternAtom(display, "_NET_WM_WINDOW_TYPE", False);
    Atom net_wm_window_type_dock = XInternAtom(display, "_NET_WM_WINDOW_TYPE_DOCK", False);

    XChangeProperty(display, window, net_wm_window_type, XA_ATOM, 32, PropModeReplace,
                    (unsigned char *)&net_wm_window_type_dock, 1);
    XSync(display, false);
}

int main() {
    Display *display = XOpenDisplay(NULL);
    if (!display) {
        fprintf(stderr, "无法打开X显示\n");
        return 1;
    }

    int screen = DefaultScreen(display);
    Window root = RootWindow(display, screen);
    unsigned long black = BlackPixel(display, screen);
    unsigned long white = WhitePixel(display, screen);

    XSetWindowAttributes  xatrs;
    xatrs.override_redirect = True;  // 禁用窗口管理器装饰
    xatrs.background_pixel = black;
    xatrs.border_pixel = white;
    xatrs.event_mask = ButtonPressMask | PointerMotionMask | ExposureMask | FocusChangeMask;
    // 创建无边框窗口
    Window window = XCreateWindow(
        display, root, 100, 100, 300, 200, 0,
        CopyFromParent, InputOutput, CopyFromParent,
        CWEventMask | /* CWOverrideRedirect  | */ CWBackPixel | CWBorderPixel, &xatrs
    );
    //Window window = XCreateSimpleWindow(display, root, 300, 300, 
    //                 600, 600, 0, black, white);
    //XSelectInput(display, window, KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask | FocusChangeMask | PropertyChangeMask | ExposureMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask);

    // 设置窗口属性
    set_always_on_top(display, window);     // 置顶
    set_no_focus(display, window);          // 不获取焦点
    //set_decorations(display, window);       // 无边框

    // 设置窗口标题
    XStoreName(display, window, "悬浮窗");

    //窗口置底
    char * prop_names[] = { "_NET_WM_STATE_BELOW", "_NET_WM_STATE_MAXIMIZED_VERT", "_NET_WM_STATE_MAXIMIZED_HORZ"};
    Atom atoms[6];
    auto ret = XInternAtoms(display, prop_names, 3, True, atoms);
    if(ret)
    {
        Atom net_wm_state = XInternAtom(display, "_NET_WM_STATE", False);
        XChangeProperty(display, window, net_wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)atoms, 1);
    }


    // 显示窗口
    XMapWindow(display, window);

    // 事件循环
    XEvent event;
    while (1) {
        XNextEvent(display, &event);

        printf("Receive X event: %d\n", event.type);
        // 处理鼠标点击事件（可选：拖动窗口）
        if (event.type == ButtonPress && event.xbutton.button == 1) {
            printf("鼠标左键点击\n");
        }

        // 主动放弃焦点（防止意外获得焦点）
        if (event.type == FocusIn) {
            //XSetInputFocus(display, PointerRoot, RevertToPointerRoot, CurrentTime);
            printf("Receive FocusIn Event\n");
        }
    }

    XCloseDisplay(display);
    return 0;
}
